//
//  WorkingMonthListController.swift
//  mggz
//
//  Created by ShareAnimation on 2017/8/25.
//  Copyright © 2017年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import MJRefresh

class WorkingMonthListController: BaseViewController {
    
    fileprivate var _tableView: UITableView!
    fileprivate var tableView: UITableView {
        get {
            if _tableView != nil {
                return _tableView
            }
            _tableView = UITableView()
            _tableView.delegate = self
            _tableView.dataSource = self
            _tableView.tableFooterView = UIView()
            _tableView.showsVerticalScrollIndicator = false
            _tableView.backgroundColor = UIColor.mg_backgroundGray
            
            regClass(_tableView, cell: UITableViewCell.self)
            regClass(_tableView, cell: AccountCalendarCell.self)
            
            return _tableView
        }
    }
    
    var currentProjectModel: ProjectModel? {
        willSet {
            if newValue != nil {
                self.currentProjectModel = newValue //注意：willSet是在属性赋值前调用的，那么如果在这里设置这条语句，那么此时调用getDate()，currentProjectModel还是Nil的
                self.getData()
            }
        }
    }
    
    var displayDate = Date() //当前界面上显示的月份。
    var recordSupplyLists: [RecordSupply]?//界面上月份对应的签到记录,日历上
    var workingMonthModel: StatisticsWorkingModel? {// 一个月的出工统计
        willSet {
            self.workingMonths = [String]()
            if newValue != nil {//将模型分解成数组
                self.workingMonths!.append(newValue!.workingDays + "天")
                self.workingMonths!.append(newValue!.workingHours + "小时")
                self.workingMonths!.append(newValue!.workingDaysNotPayed + "天")
                self.workingMonths!.append(newValue!.workingHoursNotPayed + "小时")
                self.workingMonths!.append(newValue!.payedSalaryAmount + "元")
            }
            else {
                self.workingMonths!.append("0" + "天")
                self.workingMonths!.append("0" + "小时")
                self.workingMonths!.append("0" + "天")
                self.workingMonths!.append("0" + "小时")
                self.workingMonths!.append("0" + "元")
            }
        }
    }
    
    var workingMonths: [String]?

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.mg_backgroundGray
        
        self.view.addSubview(self.tableView)
        self.tableView.snp.makeConstraints { (make) in
            make.edges.equalTo(self.view)
        }
        
        let tableHeader = MJRefreshNormalHeader { [unowned self] in
            self.getData()
        }
        tableHeader?.stateLabel.isHidden = true
        self.tableView.mj_header = tableHeader
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        WWProgressHUD.dismiss()
    }
    func getData() {
        if let model = self.currentProjectModel, let demandBaseMigrantWorkerID = model.demandBaseMigrantWorkerID  {
            
            let firstDay = displayDate.startOfMonth()
            let lastDay = displayDate.endOfMonth()
            
            let firstDayString = dateTimeToString(date: firstDay)
            let lastDayString = dateTimeToString(date: lastDay)
            
            let dispatchGroup = DispatchGroup()
            
            dispatchGroup.enter()
            //获取月历上显示的数据
            RecordSupply.getRecordStatisticInMonth(workerId: demandBaseMigrantWorkerID, startTime: firstDayString, lastTime: lastDayString){ (response) in
                if response.success {
                    self.recordSupplyLists = response.value
                    
                    
                }
                else {
                    
                    self.recordSupplyLists = nil
                }
                self.tableView.reloadData()
                dispatchGroup.leave()
            }
            
            dispatchGroup.enter()
            //获取一个月的出工情况
            StatisticsWorkingModel.getStatisticsWorkingAMonth(demandBaseMigrantWorkerID: demandBaseMigrantWorkerID, startTime: firstDayString, lastTime: lastDayString, completionHandler: { (response) in
                if response.success {
                    self.workingMonthModel = response.value   
                }
                else {
                   
                    self.workingMonthModel = nil
                }
                self.tableView.reloadSections(IndexSet.init(integer: 1), with: .automatic)
                dispatchGroup.leave()
            })
            
            dispatchGroup.notify(queue: DispatchQueue.main, execute: {
                if self.tableView.mj_header != nil {
                    self.tableView.mj_header.endRefreshing()
                }
            })
        }
    }

}

extension WorkingMonthListController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 1 {
            if let arr = self.workingMonths {
                return arr.count
            }
            return 0
        }
        return 1
    }
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 {
            return 400
        }
        return 50
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            let cell = getCell(tableView, cell: AccountCalendarCell.self, indexPath: indexPath)
            cell.recordSupplyLists = self.recordSupplyLists
            cell.blueExplainLabel.text = "已结算"
            cell.pinkExplainLabel.text = "未结算"
            cell.currentMonthChangeHandler = {[unowned self](currentDate) in
                self.displayDate = currentDate
                self.getData()
            }
            cell.selectDateHandler = {(date) in
                //let vc = RecordSupplyDisplayController()
                let vc = MemorandumListViewController(nibName: "MemorandumListViewController", bundle: nil)
                guard let model = self.currentProjectModel else {
                    WWError("请先选择项目")
                    return
                }
                vc.selectDate = date
                vc.projectModel = model
                vc.hidesBottomBarWhenPushed = true
                self.navigationController?.pushViewController(vc, animated: true)
                
            }
            return cell
        }

        if indexPath.section == 1 {
            let cell = UITableViewCell.init(style: .value1, reuseIdentifier: "\(UITableViewCell.self)")
            cell.textLabel?.text = ["本月出工天数", "本月出工工时","本月未结算天数", "本月未结算工时数",  "本月已结算工资"][indexPath.row]
            cell.textLabel?.font = wwFont_Medium(16)
            cell.detailTextLabel?.font = wwFont_Regular(16)
            
            if indexPath.row == 2 || indexPath.row == 3 {
                cell.textLabel?.textColor = UIColor.red
                cell.detailTextLabel?.textColor = UIColor.red
            }
            else {
                cell.textLabel?.textColor = UIColor.mg_lightGray
                cell.detailTextLabel?.textColor = UIColor.black
            }
            
            cell.detailTextLabel?.text = self.workingMonths![indexPath.row]
            
            return cell

        }
        return UITableViewCell()
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 0 {
            return 0.1
        }
        return 10
    }
}
